package com.iflytek.autoCompareTool.common;

import com.iflytek.autoCompareTool.model.Task;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author llchen12
 * @date 2018/6/4
 */
public class TaskManager {

    //private volatile static ConcurrentHashSet<Integer> idSet;

    private volatile static ConcurrentHashMap<Integer, Task> taskMap;


    static {
        //idSet = new ConcurrentHashSet<>();
        taskMap = new ConcurrentHashMap<>();
    }

    public static boolean containsTask(Integer id) {
        return taskMap.containsKey(id);
    }

    public static void removeTask(Integer id) {

        Task task = taskMap.remove(id);
        if (task != null) {
            ScheduledFuture<?> controller = task.getController();
            if (controller != null) {
                controller.cancel(true);
            }
        }
    }

    public static void addTask(Integer id, int size) {
        Task task = new Task(id, size);
        taskMap.put(id, task);
    }

    public static void cancelTask(Integer id) {
        Task task = taskMap.get(id);
        if (task != null) {
            task.cancel();
        }
    }

    public static boolean isCancel(Integer id) {
        Task task = taskMap.get(id);
        if (task == null) {
            return true;
        }
        return task.isCancel();
    }

    public static void addTaskController(Integer id, ScheduledFuture<?> controller) {
        Task task = taskMap.get(id);
        if (task != null) {
            task.setController(controller);
        }
    }

    public static Integer increaseAndGetTaskFinishCount(Integer id) {
        Integer res = null;
        Task task = taskMap.get(id);
        if (task != null) {
            res = task.getFinishCount().incrementAndGet();
        }
        return res;
    }

    public static Integer getAndIncreaseTaskFinishCount(Integer id) {
        Integer res = null;
        Task task = taskMap.get(id);
        if (task != null) {
            res = task.getFinishCount().getAndIncrement();
        }
        return res;
    }

    public static Double getTaskProgress(Integer id) {
        Double res = null;
        Task task = taskMap.get(id);
        if (task != null) {
            res = task.getProgress();
        }
        return res;
    }
}
